package com.zengqingfa.examples.mybatisplus.interceptor;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Order(0)
@Component
public class ControllerInteceptor {

    @Pointcut("execution(* com.zengqingfa..*.*(..)) && " +
            "(@within(org.springframework.web.bind.annotation.RestController) || " +
            "@within(org.springframework.stereotype.Controller))")
    private void Pointcut() {
        //切点
    }

    @Around(value = "Pointcut()")
    public Object target(ProceedingJoinPoint point) throws Exception {
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        Object[] args = point.getArgs();
        long startTime = System.currentTimeMillis();
        try {
            Object result = null;
            log.info("method:[{}.{}],params:[{}]", method.getDeclaringClass().getName(), method.getName(), JSONUtil.toJsonStr(args));
            result = point.proceed(args);
            log.info("method:[{}.{}],result:[{}],cost:[{}ms]", method.getDeclaringClass().getName(), method.getName(), JSONUtil.toJsonStr(result), System.currentTimeMillis() - startTime);
            return result;
        } catch (Exception e) {
            log.error("method:[{}.{}],未知异常，cost:[{}]", method.getDeclaringClass().getName(), System.currentTimeMillis() - startTime, JSONUtil.toJsonStr(e));
            throw new RuntimeException(e.getMessage());
        } catch (Throwable t) {
            log.error("method:[{}.{}],未知Throwable，cost:[{}]", method.getDeclaringClass().getName(), method.getName(), System.currentTimeMillis() - startTime, JSONUtil.toJsonStr(t));
            throw new RuntimeException(t.getMessage());
        }
    }

}
